/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ortustve.onlinescrapper.tools;

import java.io.*;
import java.net.*;
import sagex.api.Configuration;

public class urldownload extends ortustve.ortusvars {
final static int size=1024;
public static void
fileUrl(String fAddress, String
localFileName, String destinationDir) {
OutputStream outStream = null;
HttpURLConnection  uCon = null;
InputStream is = null;

long t0 = System.currentTimeMillis();

localFileName = ortustve.util.scrubString.ScrubFileName(localFileName);

try {
    URL Url;
    byte[] buf;
    int ByteRead,ByteWritten=0;
    Url= new URL(fAddress);

    File dd = new File(destinationDir.trim());

    if ( ! dd.exists() ) {
        ortustve.api.DebugLog(TRACE2,"Path: " + destinationDir.trim() + " Not Found, Creating");
        dd.mkdirs();
    }

    File df = new File(destinationDir.trim() + java.io.File.separator+localFileName);
    if ( df.exists()) {
        ortustve.api.DebugLog(INFO, "urldownload: file: " + df.getAbsolutePath() + " already exists, skipping download");
        return;
    }

    if ( ortustve.api.GetSageProperty("ortus/proxy",null) != null ) {
        String[] prox = ortustve.api.GetSageProperty("ortus/proxy",null).split(":");
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(prox[0], Integer.parseInt(prox[1])));
        uCon = (HttpURLConnection)Url.openConnection(proxy);
    } else {
        uCon = (HttpURLConnection)Url.openConnection();
    }

    uCon.setInstanceFollowRedirects(true);
    uCon.setRequestProperty("User-Agent","Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008072820 Firefox/3.0.1");
    uCon.connect();

    if ( uCon.getResponseCode() != uCon.HTTP_OK) {
        if ( uCon.getResponseCode() == uCon.HTTP_NOT_FOUND ) {
            ortustve.api.DebugLog(INFO, " URL not found" );
            return;
        }
        ortustve.api.DebugLog(ERROR, " HTTP Response: " + uCon.getResponseCode());
        ortustve.api.DebugLog(ERROR, " HTTP GET Failed");
        return;
    }

    is = uCon.getInputStream();
    outStream = new BufferedOutputStream(new FileOutputStream(destinationDir.trim()+java.io.File.separator+localFileName));

    buf = new byte[size];
    ortustve.api.DebugLog(TRACE2 ,"Staring download: " + fAddress);

    while ((ByteRead = is.read(buf)) != -1) {
        outStream.write(buf, 0, ByteRead);
        ByteWritten += ByteRead;
    }
    long t1 = System.currentTimeMillis() - t0;
    ortustve.api.DebugLog(TRACE, "Successful Download File name:\""+localFileName+ "\" No ofbytes: " + ByteWritten + " Time: " + t1 + " ms");
}
catch (Exception e) {
    ortustve.api.DebugLog(ERROR, "http download exception occured: " + e);
    try {
        is.close();
        outStream.close();
        return;
    }
    catch (IOException e2) {
        ortustve.api.DebugLog(ERROR,"http close exception: " + e2);
        return;
    }
}

   try {
//        ortus.api.DebugLog(TRACE2, "HTTP: closing connection");
        is.close();
        outStream.close();
//        ortus.api.DebugLog(TRACE2, " HTTP: closing completed");
        return;
    }
    catch (IOException e) {
        ortustve.api.DebugLog(ERROR,"http close exception: " + e);
        return;
    }
}

public static void fileDownload(String fAddress, String destinationDir)
{

  int slashIndex =fAddress.lastIndexOf('/');
int periodIndex =fAddress.lastIndexOf('.');

String fileName=fAddress.substring(slashIndex + 1);

if (periodIndex >=1 &&  slashIndex >= 0 && slashIndex < fAddress.length()-1)
{
fileUrl(fAddress,fileName,destinationDir);
}
else
{
System.err.println("path or file name.");
}}
public static void main(String[] args)
{

if(args.length==2)
{
for (int i = 1; i < args.length; i++) {
fileDownload(args[i],args[0]);
}
}
else{

}
}
 public static int CheckURL(String URL) {
      int response = 0;
     if (URL.length() == 0) {
          System.err.println
            ("Please provide a URL to check");
        } else {

            String urlString = URL;
          try {
            URL url = new URL(urlString);
            URLConnection connection =
            url.openConnection();
            if (connection instanceof HttpURLConnection) {
              HttpURLConnection httpConnection =
                 (HttpURLConnection)connection;
              httpConnection.connect();
            response =
                 httpConnection.getResponseCode();
              System.out.println(
                 "Response: " + response);
                        }
          } catch (IOException e) {
            e.printStackTrace();
          }

        }
  return response;
 }


}
